package com.backend.vse.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class WsServerHandler implements WebSocketHandler {
    private final static ConcurrentHashMap<String, WebSocketSession> list = new ConcurrentHashMap<>();

    public static void sendMessage(String message) {
        list.forEach((k, v) -> {
            try {
                v.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("ws 建立链接, {}", session.getUri());
        list.put(session.getId(), session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.info("ws消息：{}", message.getPayload());

        list.forEach((k, v) -> {
            try {
                v.sendMessage(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        list.remove(session.getId());

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
